package fortunata.jspwikiplugins.vpoet;

import com.ecyrd.jspwiki.plugin.WikiPlugin;
import com.ecyrd.jspwiki.plugin.PluginException;
import com.ecyrd.jspwiki.WikiContext;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.rdf.model.ModelFactory;

import org.apache.log4j.Logger;

import java.util.Map;
import fortunata.fswapps.vpoet.VPOETRequestData;
import fortunata.FortunataPlugin;
import fortunata.fswapps.vpoet.Vpoet;

/**
 * This plugin reads a form intended to be used by Visualization Providers (VPs).
 * The form allow VPs to insert visualizations in VPOET
 */
public class VisualizeDesign extends FortunataPlugin implements WikiPlugin {
    private static Logger log = Logger.getLogger( VisualizeDesign.class );
    private String designID, providerID, sourceURL, indvID;
    private Vpoet vpoet;

    public String execute (WikiContext context, Map parameterMap) throws PluginException {
       vpoet = new Vpoet();
       try{
            designID   = FormManager.getFieldNoEmplyValue("designID", parameterMap, "design ID");
            providerID = FormManager.getFieldNoEmplyValue("providerID", parameterMap, "provider ID");
            sourceURL  = FormManager.getFieldValue("sourceURL",  parameterMap);
            indvID  = FormManager.getFieldValue("indvID",  parameterMap);

            String requestURL= getRequestURL(context);
            //Show results message
            String
            wikiTextMessage = "%%information "+ nl +
                              "[Click here to visualize it|" + requestURL + "]" + nl +
                              "%%";
            return renderWikiText(context, wikiTextMessage);
        } catch(PluginException e){
            //Shows a nice red alert with the message.
            throw new PluginException(renderWikiText(context, e.getMessage()));
        }

    }
    private String getRequestURL(WikiContext context) throws PluginException{
        StringBuffer sb = new StringBuffer();
        String valDesignType = queryVpoetModelForDesignType(context);
        if (valDesignType == null){
           throw new PluginException("Design '"+ designID +"' created by provider '"+ providerID + "' not found");
        }else{
           sb.append(getURLBase(context) + "servlet/VPoetRequestServlet?");
           if (valDesignType.equals(VPOETRequestData.paramValueInput)){
               sb.append(VPOETRequestData.paramNameAction + "=" + VPOETRequestData.paramValueRenderInput);
           }
           if (valDesignType.equals(VPOETRequestData.paramValueOutput)){
               sb.append(VPOETRequestData.paramNameAction + "=" + VPOETRequestData.paramValueRenderOutput);
           }
           if (!valDesignType.equals(VPOETRequestData.paramValueInput) &&
               !valDesignType.equals(VPOETRequestData.paramValueOutput)){
               throw new PluginException("Design '"+ designID +"' created by provider '"+ providerID + "' has no type");
           }
        }
        sb.append("&" + VPOETRequestData.paramNameDesignID + "=" + designID);
        sb.append("&" + VPOETRequestData.paramNameProvider + "=" + providerID);
        if (sourceURL.equals("") == false){ //Is this field is not empty
            sb.append("&" + VPOETRequestData.paramNameSource + "=" + sourceURL);
        }
        if (indvID.equals("") == false){ //Is this field is not empty
             sb.append("&" + VPOETRequestData.paramNameIndvID+ "=" + indvID);
        }
        return sb.toString();
    }

    /**
     * Loads the VPOET data model and looks for the design's (designID+providerID) type (input, output..)
     * @param context
     * @return  "input", "output", etc..., or null if the individual doesn't exist
     */
    private String queryVpoetModelForDesignType(WikiContext context){
        //Creates an empty model
        OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RDFS_INF, null);
        //Reads Ontology
        vpoet.readSWAppModel(m, context);

        Individual indv = m.getIndividual(vpoet.getInstanceUniqueURI(designID, providerID));
        if (indv == null){
            return null;
        }else{
           return indv.getPropertyValue(m.getProperty(vpoet.getURI() + Vpoet.propNameDesignType)).toString();
        }
    }
}
